package com.example.androidpayment;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;

import org.json.JSONObject;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class OrderActivity extends AppCompatActivity {

    private WebView orderView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //使用支付宝的沙箱环境
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        orderView = findViewById(R.id.order);
        WebSettings settings = orderView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
        orderView.addJavascriptInterface(new OrderScript(),"order");
        orderView.loadUrl("file:///android_asset/order.html");
    }

    @Override
    protected void onResume() {
        super.onResume();
        OrderActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                orderView.loadUrl("file:///android_asset/order.html");
            }
        });
    }

    public class OrderScript{

        /**
         * @方法名：pay
         * @描述： APP支付宝支付并重新加载订单页面
         * @作者： Kuang.JiaZhuo
         * @日期： Created in 2020/6/30 22:26
         */
        @JavascriptInterface
        public void pay(String orderString,String token,String orderId){
            Runnable payRunnable = new Runnable() {
                @Override
                public void run() {
                    PayTask task = new PayTask(OrderActivity.this);
                    Map<String,String> result = task.payV2(orderString,true);
//                    System.out.println(result);
                    String resultStatus = result.get("resultStatus");
                    if(resultStatus.equals("9000")){
                        //更新订单状态
                        String path = "http://192.168.0.100:8080/parFamilyMeals/app/zfb/updateOrderStatus";
                        try {
                            URL url = new URL(path);
                            HttpURLConnection con = (HttpURLConnection) url.openConnection();
                            con.setConnectTimeout(5000);//连接的超时时间
                            con.setRequestMethod("POST");
                            JSONObject json = new JSONObject();
                            json.put("orderId",orderId);
                            con.setRequestProperty("Content-Type","application/json");
                            con.setRequestProperty("token",token);
                            /** 通过io流的方式把数据传给服务器 */
                            //允许输出流上传数据
                            con.setDoOutput(true);
                            //通过连接获得输出流
                            OutputStream out = con.getOutputStream();
                            out.write(json.toString().getBytes());
                            //关闭流
                            out.close();
                            //请求成功就刷新页面
                            if(con.getResponseCode()==200){
                                OrderActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        orderView.loadUrl("file:///android_asset/order.html");
                                    }
                                });
                            }
                            //连接用完也要关闭
                            con.disconnect();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            //异步调用
            Thread thread = new Thread(payRunnable);
            thread.start();
        }

        /**
         * @方法名：wapPay
         * @描述： 从APP唤醒打开浏览器，并跳转到银联支付页面
         * @作者： Kuang.JiaZhuo
         * @日期： Created in 2020/7/26 11:29
         */
        @JavascriptInterface
        public void wapPay(String code){
            OrderActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                   //唤醒手机浏览器，并让手机浏览器加载指定的页面
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    String url = "http://192.168.0.101:8081/parFamilyMeals/app/unionPay/htmlCodePage?code="+code;
                    Uri uri = Uri.parse(url);
                    intent.setData(uri);
                    startActivity(intent);
                }
            });
        }
    }
}
